const initSideDict = (function () {
  const initDict = () => passageDictionary(
    document.getElementById('side-menu-dict-content'),
    mdIFrame.window.document.querySelector('#write')
  )

  var transparentTimeout = null
  var lastScroll = 0

  const $sideMenu = document.getElementById('side-menu')
  const $icon = document.getElementById('side-menu-icon')
  const $content = document.getElementById('side-menu-content')

  function setTransparent() {
    console.log('setTransparent')
    addClassName($icon, 'transparent')
  }

  function removeTransparent() {
    console.log('removeTransparent')
    removeClassName($icon, 'transparent')
  }

  function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms))
  }

  function getSideMenuWidth() {
    return $content.clientWidth
  }

  async function openSideMenu() {
    removeClassName($sideMenu, 'hidden')
    $sideMenu.style.right = '-' + getSideMenuWidth() + 'px'
    await sleep(0)
    $sideMenu.style.transition = 'right 0.5s'
    await sleep(0)
    $sideMenu.style.right = '0px'
    await sleep(500)
    $sideMenu.style.transition = ''
  }

  async function closeSideMenu() {
    $sideMenu.style.right = '0px'
    await sleep(0)
    $sideMenu.style.transition = 'right 0.5s'
    await sleep(0)
    $sideMenu.style.right = '-' + getSideMenuWidth() + 'px'
    await sleep(500)
    $sideMenu.style.transition = ''
    addClassName($sideMenu, 'hidden')
    $sideMenu.style.right = '0px'
  }

  var menuClosed = true

  return function () {

    initDict()

    // watch scroll
    document.addEventListener('scroll', () => {
      const currentTime = new Date().getTime();
      if (currentTime - lastScroll < 500) return;
      setTransparent()
      if (transparentTimeout !== null) {
        clearTimeout(transparentTimeout)
      }
      transparentTimeout = setTimeout(removeTransparent, 1000)
      lastScroll = currentTime;
    })

    $icon.addEventListener('click', function () {
      if (menuClosed) {
        openSideMenu()
      } else {
        closeSideMenu()
      }
      menuClosed = !menuClosed;
    })
  }
})()
